package com.digicom.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.digicom.common.constant.Constants;
import com.digicom.common.entity.Article;
import com.digicom.common.entity.PayOrder;
import com.digicom.common.entity.User;
import com.digicom.common.exception.ServiceException;
import com.digicom.common.mapper.ArticleMapper;
import com.digicom.common.mapper.PayOrderMapper;
import com.digicom.common.mapper.UserMapper;
import com.digicom.service.order.PayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 支付订单服务实现类
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements PayOrderService {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    public Page<PayOrder> listOrderPage(PayOrder payOrder, Page<PayOrder> page) {
        return payOrderMapper.selectOrderPage(page, payOrder);
    }

    @Override
    public Page<PayOrder> listUserOrders(Long userId, Page<PayOrder> page) {
        if (userId == null) {
            throw new ServiceException("用户ID不能为空");
        }
        return payOrderMapper.selectUserOrders(page, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(PayOrder payOrder) {
        if (payOrder == null || payOrder.getUserId() == null || payOrder.getArticleId() == null) {
            throw new ServiceException("订单信息不完整");
        }

        // 查询用户信息
        User user = userMapper.selectById(payOrder.getUserId());
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 查询文章信息
        Article article = articleMapper.selectById(payOrder.getArticleId());
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        // 检查文章是否需要付费
        if (!Constants.ARTICLE_TYPE_PAID.equals(article.getArticleType())) {
            throw new ServiceException("该文章无需付费");
        }

        // 检查用户是否已购买该文章
        LambdaQueryWrapper<PayOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PayOrder::getUserId, payOrder.getUserId())
               .eq(PayOrder::getArticleId, payOrder.getArticleId())
               .eq(PayOrder::getOrderStatus, Constants.PAY_STATUS_SUCCESS);
        if (count(wrapper) > 0) {
            throw new ServiceException("您已购买过该文章");
        }

        // 生成订单
        String orderNo = generateOrderNo();
        payOrder.setOrderNo(orderNo);
        payOrder.setUserName(user.getUsername());
        payOrder.setArticleTitle(article.getTitle());
        payOrder.setAmount(article.getPrice());
        payOrder.setOrderStatus(Constants.PAY_STATUS_PENDING);
        payOrder.setRefundStatus(Constants.REFUND_STATUS_NO);

        // 保存订单
        save(payOrder);

        return payOrder.getOrderId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(String orderNo, String payType, String tradeNo) {
        if (StringUtils.isBlank(orderNo) || StringUtils.isBlank(tradeNo)) {
            throw new ServiceException("参数不能为空");
        }

        // 查询订单信息
        PayOrder payOrder = getByOrderNo(orderNo);
        if (payOrder == null) {
            throw new ServiceException("订单不存在");
        }

        // 检查订单状态
        if (Constants.PAY_STATUS_SUCCESS.equals(payOrder.getOrderStatus())) {
            return true; // 订单已支付成功，直接返回成功
        }

        // 更新订单状态
        payOrder.setOrderStatus(Constants.PAY_STATUS_SUCCESS);
        payOrder.setPayType(payType);
        payOrder.setTradeNo(tradeNo);
        payOrder.setPayTime(new Date());

        boolean result = updateById(payOrder);
        if (result) {
            // 支付成功后，通知APP同步订单数据
            kafkaTemplate.send(Constants.TOPIC_ORDER_SYNC, payOrder);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refundOrder(String orderNo, String refundReason) {
        if (StringUtils.isBlank(orderNo)) {
            throw new ServiceException("订单号不能为空");
        }

        // 查询订单信息
        PayOrder payOrder = getByOrderNo(orderNo);
        if (payOrder == null) {
            throw new ServiceException("订单不存在");
        }

        // 检查订单状态
        if (!Constants.PAY_STATUS_SUCCESS.equals(payOrder.getOrderStatus())) {
            throw new ServiceException("订单未支付成功，不能退款");
        }

        if (Constants.REFUND_STATUS_SUCCESS.equals(payOrder.getRefundStatus())) {
            throw new ServiceException("订单已退款");
        }

        // 执行退款操作，调用支付平台退款接口
        // 模拟退款成功
        boolean refundSuccess = true;
        
        if (refundSuccess) {
            // 更新订单退款状态
            payOrder.setRefundStatus(Constants.REFUND_STATUS_SUCCESS);
            payOrder.setRefundTime(new Date());
            payOrder.setRefundReason(refundReason);
            
            boolean result = updateById(payOrder);
            if (result) {
                // 退款成功后，通知APP同步订单数据
                kafkaTemplate.send(Constants.TOPIC_ORDER_SYNC, payOrder);
            }
            return result;
        }
        
        return false;
    }

    @Override
    public PayOrder getByOrderNo(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            throw new ServiceException("订单号不能为空");
        }
        return payOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public Map<String, Object> statisticPayAmount(Date beginDate, Date endDate) {
        // 将Date转换为yyyy-MM-dd格式的字符串
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
        String startDate = beginDate != null ? dateFormat.format(beginDate) : null;
        String endDateStr = endDate != null ? dateFormat.format(endDate) : null;
        
        // 查询统计数据
        List<Map<String, Object>> statsList = payOrderMapper.statisticPayAmount(startDate, endDateStr);
        
        // 汇总数据
        Map<String, Object> result = new HashMap<>();
        
        // 支付总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        // 支付宝金额
        BigDecimal alipayAmount = BigDecimal.ZERO;
        // 微信支付金额
        BigDecimal wxpayAmount = BigDecimal.ZERO;
        
        for (Map<String, Object> stats : statsList) {
            BigDecimal amount = (BigDecimal) stats.get("amount");
            String payType = (String) stats.get("pay_type");
            
            totalAmount = totalAmount.add(amount);
            
            if ("1".equals(payType)) {
                alipayAmount = alipayAmount.add(amount);
            } else if ("2".equals(payType)) {
                wxpayAmount = wxpayAmount.add(amount);
            }
        }
        
        result.put("totalAmount", totalAmount);
        result.put("alipayAmount", alipayAmount);
        result.put("wxpayAmount", wxpayAmount);
        result.put("detailList", statsList);
        
        return result;
    }

    /**
     * 生成订单号
     * 
     * @return 订单号
     */
    private String generateOrderNo() {
        // 生成格式：yyyyMMddHHmmss + 6位随机数
        String dateStr = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String randomStr = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        return dateStr + randomStr;
    }
    
    /**
     * 支付回调处理
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean payCallback(String orderNo, String tradeNo, String payTime) {
        if (StringUtils.isBlank(orderNo) || StringUtils.isBlank(tradeNo)) {
            throw new ServiceException("参数不能为空");
        }

        // 查询订单信息
        PayOrder payOrder = getByOrderNo(orderNo);
        if (payOrder == null) {
            throw new ServiceException("订单不存在");
        }

        // 检查订单状态
        if (Constants.PAY_STATUS_SUCCESS.equals(payOrder.getOrderStatus())) {
            return true; // 订单已支付成功，直接返回成功
        }

        // 更新订单状态
        int rows = payOrderMapper.updateOrderStatus(orderNo, Constants.PAY_STATUS_SUCCESS, payTime, tradeNo);
        if (rows > 0) {
            // 支付成功后，通知APP同步订单数据
            kafkaTemplate.send(Constants.TOPIC_ORDER_SYNC, payOrder);
            return true;
        }
        
        return false;
    }
    
    /**
     * 创建订单
     */
    @Transactional(rollbackFor = Exception.class)
    public PayOrder createOrder(Long userId, Long articleId, String payType, String clientType) {
        if (userId == null || articleId == null || StringUtils.isBlank(payType)) {
            throw new ServiceException("参数不能为空");
        }

        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 查询文章信息
        Article article = articleMapper.selectById(articleId);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }

        // 检查文章是否需要付费
        if (!Constants.ARTICLE_TYPE_PAID.equals(article.getArticleType())) {
            throw new ServiceException("该文章无需付费");
        }

        // 检查用户是否已购买该文章
        LambdaQueryWrapper<PayOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PayOrder::getUserId, userId)
               .eq(PayOrder::getArticleId, articleId)
               .eq(PayOrder::getOrderStatus, Constants.PAY_STATUS_SUCCESS);
        if (count(wrapper) > 0) {
            throw new ServiceException("您已购买过该文章");
        }

        // 生成订单
        PayOrder payOrder = new PayOrder();
        payOrder.setOrderNo(generateOrderNo());
        payOrder.setUserId(userId);
        payOrder.setUserName(user.getUsername());
        payOrder.setArticleId(articleId);
        payOrder.setArticleTitle(article.getTitle());
        payOrder.setAmount(article.getPrice());
        payOrder.setPayType(payType);
        payOrder.setClientType(clientType);
        payOrder.setOrderStatus(Constants.PAY_STATUS_PENDING);
        payOrder.setRefundStatus(Constants.REFUND_STATUS_NO);

        // 保存订单
        save(payOrder);

        return payOrder;
    }
    
    /**
     * 订单分页查询
     */
    public Page<PayOrder> getOrderPage(PayOrder order, Page<PayOrder> page) {
        return payOrderMapper.selectOrderPage(page, order);
    }
    
    /**
     * 获取订单详细信息
     */
    public PayOrder getOrderByNo(String orderNo) {
        return getByOrderNo(orderNo);
    }
} 